package com.yu.crm.ws.pw;

import com.yu.crm.service.impl.CrmEigenvalueService;
import com.yu.crm.ws.WebSocketManager;
import com.yu.crm.ws.WsMessage;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.JsonHelpers;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;

//import java.util.Base64;

/**
 * 模块名称：WS服务端
 * 功能说明：
 *
 * @Author: bin-donnie
 * @Date: 2019/7/4 5:23 PM
 */


@ServerEndpoint(value = "/websocketPW/{sid}")
@Component
@Log4j2
public class WebSocketClientPW {
    @Resource
    private CrmEigenvalueService crmEigenvalueService;

    private static WebSocketClientPW webSocketClient;


    //当前会话
    private Session session;

    //当前sid
    private String sid;

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    /**
     * 实例化service对象
     */
    @PostConstruct
    public void init() {
        webSocketClient = this;
        webSocketClient.crmEigenvalueService = this.crmEigenvalueService;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String sid) {
        this.setSession(session);
        this.setSid(sid);
        WebSocketManagerPW.addClient(this);
        log.info("WS 连接成功, sid={}, 在线数量={}", sid, WebSocketManagerPW.getOnlineCount());
        WebSocketManagerPW.onOpen();
    }

    @OnClose
    public void onClose() {
        WebSocketManagerPW.removeClient(this);
        log.info("WS 连接关闭, 在线数量={}", WebSocketManagerPW.getOnlineCount());
        WebSocketManagerPW.onClose();
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("WS 收到消息:{}, sid={}", message, sid);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WS 发生错误:{}", error.getMessage());
    }

}
